package cn.smile.commons.encrypt.service.impl;

import cn.smile.commons.encrypt.service.EncryptService;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class Base64EncryptService implements EncryptService {
    @Override
    public String encrypt(String content) {
        try {
            return Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            log.error("Base64 加密失败, e:", e);
            throw new BusinessException(MyResponseCode.DATABASE_FIELD_ENCRYPT_BASE64);
        }
    }

    @Override
    public String decrypt(String content) {
        try {
            byte[] asBytes = Base64.getDecoder().decode(content);
            return new String(asBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("Base64 解密失败, e:", e);
            throw new BusinessException(MyResponseCode.DATABASE_FIELD_DECRYPT_BASE64);
        }
    }
}
